const formatAddrData = {
    addrData: null,
    addrNameMap: null,
    defaultOption : {
        overSeaIndex: '0',
        countryIndex: '1',
        overSeaCode: '990000'
    },
    initData: function (json) {
        //省市区可认为当前生命周期内不可变，如果已经初始化过数据，不重复调用
        if (this.addrData || this.addrNameMap) return;
         console.log('initData',json);
            var res = {}, map = {}, list = json.data.list;
            for (var i=0; i<list.length; i++) {
                res[list[i]['id']] = [list[i]['name'], list[i]['parentId']];
                map[list[i]['name']] = list[i]['id'];
            }
            this.addrData = res;
            this.addrNameMap = map;
         
    },
    _parseData: function(addrCode, renderUI) {
        var nameCode = {}, arr=[];
        for (var key in this.addrData) {
            if (this.addrData.hasOwnProperty(key)) {
                var valueArray = this.addrData[key];
                if (valueArray[1] == addrCode) {
                    nameCode[valueArray[0]] = key;
                    arr.push({
                        'label': valueArray[0],
                        'value': key
                    });
                }
            }
        }
        return arr;
    },
    //省
    getProvinceByCode: function(countryIndex) {
        return this._parseData(countryIndex);
    },
    //市
    getCityByProCode: function(proCode) {
        return this._parseData(proCode);
    },
    //区 好吧都一样
    getAreaByCityCode: function(cityCode) {
        return this._parseData(cityCode);
    },
    //根据省份名字获取code
    getProCodeByName: function(proName) {
        for (var key in this.addrData) {
            if (this.addrData[key][0] === proName) {
                return key;
            }
        }
    },
    //自动匹配省市区地址
    autoMatchAddress: function(allAddress) {
        let address = {};
        let province = allAddress.substr(0, 2);
        let provinceMap = this.getProvinceByCode('1');
        let matchProvince = provinceMap.find((item) => { return item.label.indexOf(province) > -1 }) || { label: '', value: '' };
        if (matchProvince.label.length > 0) {
            address['receiverState'] = matchProvince.label;
            allAddress = allAddress.indexOf(matchProvince.label) > -1 ? allAddress.substr(allAddress.indexOf(matchProvince.label) + matchProvince.label.length) : allAddress;
            let cityMap = this.getCityByProCode(matchProvince.value);
            let matchCityArr = cityMap.filter((item) => { return allAddress.indexOf(item.label.substr(0, 2)) > -1 });
            let matchCity = { label: '', value: '' };
            //王青海 18344556677 浙江省 嘉兴市 南湖区 南湖街道花园路518号温州大厦D幢绍兴门11111号
            if (matchCityArr.length == 1) {
                matchCity = matchCityArr[0];
            } else if (matchCityArr.length > 1) {
                let pos = 30, inde = 0;//温州 和 嘉兴 出现位置靠前为城市
                //如果是吉林省，删除allAddress的首位吉林，防止吉林市的误判
                if (allAddress.indexOf('吉林') == 0 && allAddress.indexOf('吉林市') != 0) allAddress=allAddress.substr(2);
                matchCityArr.forEach((item, index) => {
                    let p = allAddress.indexOf(item.label.substr(0, 2));
                    if (p < pos && p > -1) {
                        pos = p;
                        inde = index;
                    }
                })
                matchCity = matchCityArr[inde];
            }

            if (matchCity.label.length > 0) {
                address['receiverCity'] = matchCity.label;
                allAddress = allAddress.indexOf(matchCity.label) > -1 ? allAddress.substr(allAddress.indexOf(matchCity.label) + matchCity.label.length) : allAddress;
                let areaMap = this.getAreaByCityCode(matchCity.value);
                let matchArea = areaMap.find((item) => { return allAddress.indexOf(item.label.substr(0, 3)) > -1 }) || { label: '', value: '' };
                address['receiverDistrict'] = matchArea.label;
                allAddress = allAddress.indexOf(matchArea.label) > -1 ? allAddress.substr(allAddress.indexOf(matchArea.label) + matchArea.label.length) : allAddress;
            }
        }
        address['receiverAddress'] = allAddress.trim();
        address['receiverState'] = address['receiverState'] || '';
        address['receiverCity'] = address['receiverCity'] || '';
        address['receiverDistrict'] = address['receiverDistrict'] || '';
        return address;
    },
    //自动识别地址
    autoReadAddress: function (_value = ''){
        let address = {};
        let _valueArray = _value.trim().replace(/,/ig, ' ').replace(/，/ig, ' ').replace(/[|]*\n/, " ").replace(/&nbsp;/ig, " ").replace(/\s+/g, " ").replace(/\u200B/g,'').split(" ");

        //先抽离能识别的
        let indexPhone = -1, indexMobile = -1;
        //let indexZip = -1;
        let matchedObj = {
            receiverName: '',
            receiverMobile: '',
            receiverPhone: '',
            receiverZip: ''
        };
        _valueArray.forEach((value, index) => {
            if (/^((\+?86)|(\(\+86\))|(86-))?1[3456789]\d{9}$/.test(value)) {
                indexPhone = index;
                matchedObj.receiverMobile = value.indexOf('+86') === 0 || value.indexOf('86-') === 0 ? value.substr(3) : value;
                _valueArray[index] = '';
            }
            if (/^0\d{2,3}-?\d{7,8}$/.test(value)) {
                indexMobile = index;
                matchedObj.receiverPhone = value;
                _valueArray[index] = '';
            }
            if (/^[0-9]{6}$/.test(value)) {
                //indexZip = index;
                matchedObj.receiverZip = value;
                _valueArray[index] = '';
            }
        })
        //有号码且第一位不是号码，把第一位当做姓名
        if (indexPhone > 0 || indexMobile > 0) {
            matchedObj.receiverName = _valueArray[0];
            _valueArray[0] = '';
        }

        //有号码才算插入匹配值，否则不匹配
        if (indexPhone > -1 || indexMobile > -1) {
            Object.assign(address, matchedObj);
        } else {
            return false;
        }

        //拿到剩余字段，非汉字开头的排到后面
        let _valueArrayAddr = _valueArray.filter(val => { return val != '' });
        let isNumFirst = [];
        let isnotNumFirst = [];
        let character = /[^\u4e00-\u9fa5]/;
        _valueArrayAddr.forEach((value, index) => {
            if (isnotNumFirst.length > 0 || !character.test(value.substr(0, 1))) {
                isnotNumFirst.push(value);
            } else {
                isNumFirst.push(value);
            }
        });
        let resArr = isnotNumFirst.concat(isNumFirst);

        //匹配省市区
        let res = this.autoMatchAddress(resArr.join(''));
        Object.assign(address, res);
        return address;
    },
};

export default formatAddrData;
